export class ChromePortStream {
    constructor(port) {
        this._port = port;
    }

    get readable() {
        let _controller = null;
        let _eventHandler = function (data) {
            let { type, chunk } = data;
            if (type === 'stream') {
                _controller.enqueue(new Uint8Array(chunk.data));
                // _controller.enqueue(chunk);
            }
        }
        return new ReadableStream({
            start: (controller) => {
                _controller = controller;
                this._port.onMessage.removeListener(_eventHandler);
                this._port.onMessage.addListener(_eventHandler);
            },
            cancel: () => {
                this._port.onMessage.removeListener(_eventHandler);
                this._port.disconnect();
            }
        });
    }

    get writable() {
        return new WritableStream({
            write: (chunk) => {
                // this._port.postMessage({ type: 'stream', chunk:Array.from(chunk) });
                this._port.postMessage({ type: 'stream', chunk });
            }
        });
    }
}